<?php

namespace App\Http\Controllers\Api;

use App\User;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;


class TokenController extends BaseController
{
    public function __construct()
    {
        $this->middleware('auth')->except('login', 'register');
    }

    // 如果想要使用 name 作为登录的凭据（那么意味着注册时可能会没有 email，就要修改表结构了）
    protected function username()
    {
        return 'email';
    }


    public function dluoRegister(Request $request)
    {
        try {
            $this->validator($request->all())->validate();

            $api_token = $this->dluoRandomString();
            $data = array_merge($request->all(), compact('api_token'));
            if (!empty(config('api.token.expires_in'))) {
                $data = array_merge($data, ['expires_at' => $this->dluoDateFull(time() + config('api.token.expires_in'))]);
            }
            $this->dluoSave($data);

            return $this->dluoSuccess(compact('api_token'));
        } catch (\Exception $e) {
            return $this->logException(__METHOD__, $e);
        }
    }

    protected function dluoValidator($data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255', 'unique:users',],
            'email' => ['required', 'string', 'email', 'max:255',],
            'password' => ['required', 'string', 'min:8', 'confirmed'],// 还需要 password_confirmation 字段。
        ]);
    }

    protected function dluoSave($data)
    {
        return User::forceCreate([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => password_hash($data['password'], PASSWORD_DEFAULT),
            'api_token' => $this->dluoHashToken($data['api_token']),
        ]);
    }

    public function dluoLogin()
    {
        try {
            $user = User::where($this->username(), request($this->username()))->firstOrFail();

            if (!password_verify(request('password'), $user->password)) {
                return $this->dluoError(40001, '参数错误');
            }

            $api_token = $this->dluoRandomString();
            $user->update(['api_token' => $this->dluoHashToken($api_token)]);

            return $this->dluoSuccess(compact('api_token'));
        } catch (\Exception $e) {
            return $this->dluoException(__METHOD__, $e->getMessage());
        }
    }

    public function dluoLogout()
    {
        try {
            auth()->user()->update(['api_token' => null]);

            return $this->dluoSuccessMessage('退出成功');
        } catch (\Exception $e) {
            return $this->dluoException(__METHOD__, $e->getMessage());
        }
    }

    public function dluoRefresh()
    {
        try {
            $api_token = $this->dluoRandomString();

            auth()->user()->update(['api_token' => $this->dluoHashToken($api_token)]);

            return $this->dluoSuccess(compact('api_token'));
        } catch (\Exception $e) {
            return $this->dluoException(__METHOD__, $e->getMessage());
        }
    }

    private function dluoHashToken($apiToken) {
        return hash('sha256', $apiToken);
    }
}